In C++, a do-while loop is a control structure that is similar to the while loop. The primary difference is that in a do-while loop, the condition is evaluated after the loop body is executed. This ensures that the loop body is executed at least once, even if the condition is initially false. Here's the basic syntax of a do-while loop:
do {
// Code to be executed
} while (condition);
condition: A Boolean expression that is evaluated after each execution of the loop body. If the condition is true, the loop continues; if it's false, the loop terminates.
Here's an example of a do-while loop that asks the user to enter a positive number and continues to do so until a negative number is entered:
#include <iostream>
int main() {
int num;
do {
std::cout << "Enter a positive number (enter a negative number to stop): ";
std::cin >> num;
if (num >= 0) {
std::cout << "entered: " << num << std::endl;
}
} while (num >= 0);
std::cout << "Loop finished." << std::endl;
return 0;
}
In this example, the loop body prompts the user for input and displays the entered number. The loop continues to execute until the user enters a negative number, at which point the loop terminates.
question
question2